<?php

namespace app\api\controller;

use app\admin\model\Equity;
use app\common\model\User;
use app\admin\model\WechatUser;
use app\admin\model\UserRefund;
use app\admin\model\Order;
use app\admin\model\UserRelation;
use app\common\controller\Api;
use fast\Random;
use Overtrue\Socialite\AuthorizeFailedException;
use think\Exception;
use fast\Http;
use EasyWeChat\Factory;
use dh2y\qrcode\QRcode;
use app\service\FXApiService;
use app\service\IyunBinkService;
/**
 * Token接口
 */
class Apiminiapp extends Api
{
    protected $noNeedLogin = ["getuserinfo", 'login','getiyunlogin','getfxlogin'];
    protected $noNeedRight = '*';
    protected $user;
    protected $wechat_user;
    protected $app;

    protected function _initialize()
    {

        parent::_initialize();
        $this->app = Factory::officialAccount(config('wechat'));
        $token = $this->auth->getToken();
        if ($token) {
            $this->user = $this->auth->getUser();
            $this->wechat_user =  unserialize(cache("WECHAT_USER_" . $token));
            $this->auth->init($token);
        }
    }
    public function login()
    {

        // $code = $this->request->request("code");
        $oauth = $this->app->oauth;

        // 获取 OAuth 授权结果用户信息、
        try {
            $user = $oauth->user()->toArray();
        } catch (AuthorizeFailedException $e) {

            $err_arr = json_decode(str_replace("Authorize Failed: ", "", $e->getMessage()), true);
            // var_dump($err_arr);
            return $this->error("授权错误：" . $err_arr["errmsg"]);
        }
        $wechat_user =  WechatUser::where("openid", $user["id"])->find();
        if (!$wechat_user) {
            $save_data = [
                "openid" => $user["id"],
                "nickname" => $user["name"],
                "sex" => $user["original"]["sex"],
                "language" => $user["original"]["language"],
                "city" => $user["original"]["city"],
                "province" => $user["original"]["province"],
                "country" => $user["original"]["country"],
                "headimgurl" => $user["original"]["headimgurl"],
            ];

            //创建微信用户
            $wechat_user = WechatUser::create($save_data);
            //创建用户表用户
            $wechat_user->save();
        } else {
            if ($wechat_user->user_id) {
                $this->auth->direct($wechat_user->user_id);
            } else {
                $wechat_user->save();
            }
        }
        $wechat_user =  WechatUser::where("openid", $user["id"])->find();
        $token = $this->auth->getToken();
        cache("WECHAT_USER_" . $token, serialize($wechat_user));
        return $this->success("用户信息获取成功", ["token" => $token, "wechat_user" => [
            "nickname" => $wechat_user->nickname,
            "user_id" => $wechat_user->user_id,
            "mobile" => $wechat_user->mobile,
            "sex" => $wechat_user->sex,
            "language" => $wechat_user->language,
            "province" => $wechat_user->province,
            "city" => $wechat_user->city,
            "country" => $wechat_user->country,
            "headimgurl" => $wechat_user->headimgurl,
            "sex_text" => $wechat_user->sex_text,
            "createtime" => $wechat_user->createtime,
            "updatetime" => $wechat_user->updatetime,
            "openid" => $wechat_user->openid,
        ]]);
    }
    /**
     * 用户数据查询
     *
     * @return void
     */
    public function getuserinfo()
    {
        $this->user = $this->auth->getUser();
        if ($this->user) {
            $this->success('成功', $this->user);
        } else {
            $this->error(__('You are not logged in'));
        }
    }
    /**
     * 领取明细
     *
     * @return void
     */
    public function getUserRefund()
    {
        $pagesize = $this->requestdata('pagesize');
        $refundModel = new UserRefund();
        $data = $refundModel->getSelect(['user_id' => $this->user->id, 'status' => ['=', '2']], $pagesize);
        if ($data) {
            $this->success('成功', $data);
        } else {
            $this->error('未找到数据');
        }
    }
    /**
     * 推广明细
     *
     * @return void
     */
    public function getUserRec()
    {
        $pagesize = $this->requestdata('pagesize');
        $userList = User::where('rec_user_id', $this->user->id)->select();
        if (!$userList) {
            $this->error('未找到数据');
        }
        $data = [];
        foreach ($userList as $k => $l) {
            $data[$k]['username'] = $l->username;
            $data[$k]['phone'] = $l->mobile;
            $orderm = Order::alias('a')->join('equity b', 'a.id=b.order_id', 'left')->where(['a.user_id' => $l->id, 'a.status' => '2', 'b.user_id' => $this->user->id, 'b.date' => ['>=', date('YM01', time())]])->sum('fee');
            $orderm = round($orderm, 2);
            $data[$k]['m_money'] = $orderm == 0 ? 0.00 : $orderm;
            $ordery = Order::alias('a')->join('equity b', 'a.id=b.order_id', 'left')->where(['a.user_id' => $l->id, 'a.status' => '2', 'b.user_id' => $this->user->id, 'b.date' => ['>=', date('Y0101', time())]])->sum('fee');
            $ordery = round($ordery, 2);
            $data[$k]['y_money'] = $ordery == 0 ? 0.00 : $ordery;
        }

        if ($data) {
            $this->success('成功', $data);
        } else {
            $this->error('未找到数据');
        }
    }
    /**
     * 提现
     *
     * @return void
     */
    public function setRefund()
    {
        $money = $this->requestdata('money');
        if ($this->user->money < $money) {
            $this->error('提现金额不足');
        }
        if ($money < 1) {
            $this->error('提现不能小于1');
        }
        $bank_map = ["CDB" => "国家开发银行", "ICBC" => "中国工商银行", "ABC" => "中国农业银行", "BOC" => "中国银行", "CCB" => "中国建设银行", "PSBC" => "中国邮政储蓄银行", "COMM" => "交通银行", "CMB" => "招商银行", "SPDB" => "上海浦东发展银行", "CIB" => "兴业银行", "HXBANK" => "华夏银行", "GDB" => "广东发展银行", "CMBC" => "中国民生银行", "CITIC" => "中信银行", "CEB" => "中国光大银行", "EGBANK" => "恒丰银行", "CZBANK" => "浙商银行", "BOHAIB" => "渤海银行", "SPABANK" => "平安银行", "SHRCB" => "上海农村商业银行", "YXCCB" => "玉溪市商业银行", "YDRCB" => "尧都农商行", "BJBANK" => "北京银行", "SHBANK" => "上海银行", "JSBANK" => "江苏银行", "HZCB" => "杭州银行", "NJCB" => "南京银行", "NBBANK" => "宁波银行", "HSBANK" => "徽商银行", "CSCB" => "长沙银行", "CDCB" => "成都银行", "CQBANK" => "重庆银行", "DLB" => "大连银行", "NCB" => "南昌银行", "FJHXBC" => "福建海峡银行", "HKB" => "汉口银行", "WZCB" => "温州银行", "QDCCB" => "青岛银行", "TZCB" => "台州银行", "JXBANK" => "嘉兴银行", "CSRCB" => "常熟农村商业银行", "NHB" => "南海农村信用联社", "CZRCB" => "常州农村信用联社", "H3CB" => "内蒙古银行", "SXCB" => "绍兴银行", "SDEB" => "顺德农商银行", "WJRCB" => "吴江农商银行", "ZBCB" => "齐商银行", "GYCB" => "贵阳市商业银行", "ZYCBANK" => "遵义市商业银行", "HZCCB" => "湖州市商业银行", "DAQINGB" => "龙江银行", "JINCHB" => "晋城银行JCBANK", "ZJTLCB" => "浙江泰隆商业银行", "GDRCC" => "广东省农村信用社联合社", "DRCBCL" => "东莞农村商业银行", "MTBANK" => "浙江民泰商业银行", "GCB" => "广州银行", "LYCB" => "辽阳市商业银行", "JSRCU" => "江苏省农村信用联合社", "LANGFB" => "廊坊银行", "CZCB" => "浙江稠州商业银行", "DYCB" => "德阳商业银行", "JZBANK" => "晋中市商业银行", "BOSZ" => "苏州银行", "GLBANK" => "桂林银行", "URMQCCB" => "乌鲁木齐市商业银行", "CDRCB" => "成都农商银行", "ZRCBANK" => "张家港农村商业银行", "BOD" => "东莞银行", "LSBANK" => "莱商银行", "BJRCB" => "北京农村商业银行", "TRCB" => "天津农商银行", "SRBANK" => "上饶银行", "FDB" => "富滇银行", "CRCBANK" => "重庆农村商业银行", "ASCB" => "鞍山银行", "NXBANK" => "宁夏银行", "BHB" => "河北银行", "HRXJB" => "华融湘江银行", "ZGCCB" => "自贡市商业银行", "YNRCC" => "云南省农村信用社", "JLBANK" => "吉林银行", "DYCCB" => "东营市商业银行", "KLB" => "昆仑银行", "ORBANK" => "鄂尔多斯银行", "XTB" => "邢台银行", "JSB" => "晋商银行", "TCCB" => "天津银行", "BOYK" => "营口银行", "JLRCU" => "吉林农信", "SDRCU" => "山东农信", "XABANK" => "西安银行", "HBRCU" => "河北省农村信用社", "NXRCU" => "宁夏黄河农村商业银行", "GZRCU" => "贵州省农村信用社", "FXCB" => "阜新银行", "HBHSBANK" => "湖北银行黄石分行", "ZJNX" => "浙江省农村信用社联合社", "XXBANK" => "新乡银行", "HBYCBANK" => "湖北银行宜昌分行", "LSCCB" => "乐山市商业银行", "TCRCB" => "江苏太仓农村商业银行", "BZMD" => "驻马店银行", "GZB" => "赣州银行", "WRCB" => "无锡农村商业银行", "BGB" => "广西北部湾银行", "GRCB" => "广州农商银行", "JRCB" => "江苏江阴农村商业银行", "BOP" => "平顶山银行", "TACCB" => "泰安市商业银行", "CGNB" => "南充市商业银行", "CCQTGB" => "重庆三峡银行", "XLBANK" => "中山小榄村镇银行", "HDBANK" => "邯郸银行", "KORLABANK" => "库尔勒市商业银行", "BOJZ" => "锦州银行", "QLBANK" => "齐鲁银行", "BOQH" => "青海银行", "YQCCB" => "阳泉银行", "SJBANK" => "盛京银行", "FSCB" => "抚顺银行", "ZZBANK" => "郑州银行", "SRCB" => "深圳农村商业银行", "BANKWF" => "潍坊银行", "JJBANK" => "九江银行", "JXRCU" => "江西省农村信用", "HNRCU" => "河南省农村信用", "GSRCU" => "甘肃省农村信用", "SCRCU" => "四川省农村信用", "GXRCU" => "广西省农村信用", "SXRCCU" => "陕西信合", "WHRCB" => "武汉农村商业银行", "YBCCB" => "宜宾市商业银行", "KSRB" => "昆山农村商业银行", "SZSBK" => "石嘴山银行", "HSBK" => "衡水银行", "XYBANK" => "信阳银行", "NBYZ" => "鄞州银行", "ZJKCCB" => "张家口市商业银行", "XCYH" => "许昌银行", "JNBANK" => "济宁银行", "CBKF" => "开封市商业银行", "WHCCB" => "威海市商业银行", "HBC" => "湖北银行", "BOCD" => "承德银行", "BODD" => "丹东银行", "JHBANK" => "金华银行", "BOCY" => "朝阳银行", "LSBC" => "临商银行", "BSB" => "包商银行", "LZYH" => "兰州银行", "BOZK" => "周口银行", "DZBANK" => "德州银行", "SCCB" => "三门峡银行", "AYCB" => "安阳银行", "ARCU" => "安徽省农村信用社", "HURCB" => "湖北省农村信用社", "HNRCC" => "湖南省农村信用社", "NYNB" => "广东南粤银行", "LYBANK" => "洛阳银行", "NHQS" => "农信银清算中心", "CBBQS" => "城市商业银行资金清算中心"];
        $data = [
            'cardNo' => $this->user->bank_card,
            'cardBinCheck' => 'true'
        ];
        $http = Http::get("https://ccdcapi.alipay.com/validateAndCacheCardInfo.json", $data, ['Content-type: application/json']);
        $data = json_decode($http, true);

        if ($data['validated'] == false) {
            $this->error(__('Bankcard in failed'));
        } else {
            $bank_short = $data['bank'];
            $bank_name = $bank_map[$data['bank']];
        }
        $refundModel = new UserRefund();
        $data = $refundModel->setCreate($this->user->id, $money, $this->user->bank_card, $bank_name, $this->user->username, $this->user->mobile, $this->user->sub_branch);

        if ($data['res'] == true) {
            User::jiemoney($money, $this->user->id, $this->user->username . '提现' . $money);
            return $this->success('成功', $data);
        } else {
            return $this->error('添加失败');
        }
    }
    /**
     * 生成推广二维码
     *
     * @return void
     */
    public function QrcodeUrl()
    {
        if (!$this->user->rec_code) {

            $code = new QRcode();
            $res = $code->png('http://weiqq.nat300.top#/pages/Invite/index?phone=' . $this->user->mobile, false, 6)->entry();
            $user['rec_code'] = $res;
            User::where('id', $this->user->id)->update($user);
            return $this->success('成功', $res);
        } else {
            return $this->success('成功', $this->user->rec_code);
        }
    }
    /**
     * i云服登录h5页面
     *
     * @return void
     */
    public function getiyunlogin()
    {
        $user_id = $this->requestdata('user_id');
        $user=User::where('id',$user_id)->find();
        if(empty($user)){
            $this->error('未找到用户');
        }
        $userrelation=new UserRelation();
        $tion=$userrelation->where('user_id',$user_id)->find();
        if(is_null($tion)){
            $this->error('请通知工作人员帮忙绑定');
        }
        $data=IyunBinkService::getH5Login($tion->t_id);
        return $this->success('成功', $data);
    }
    /**
     * fx登录登录h5页面
     *
     * @return void
     */
    public function getfxlogin()
    {
        $user_id = $this->requestdata('user_id');
        $user=User::where('id',$user_id)->find();
        if(empty($user)){
            $this->error('未找到用户');
        }
        $userrelation=new UserRelation();
        $tion=$userrelation->where('user_id',$user_id)->find();
        if(is_null($tion)){
            $this->error('请通知工作人员帮忙绑定');
        }
        $data=FXApiService::getH5Login($user->mobile);
        return $this->success('成功', $data);
    }
    protected function requestdata($key, $default = "")
    {
        return  input($key, $default);
    }
}
